package com.jstyle.jclife.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.jstyle.countrylibrary.CountryPage;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.NetWork.api.JstyleApi;
import com.jstyle.jclife.R;
import com.jstyle.jclife.model.ActionData;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SHA1;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.EditTextWithDelete;
import com.mob.tools.FakeActivity;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 找回密码
 */
public class FindPasswordActivity extends BaseActivity {
    private static final String TAG = "FindPasswordActivity";

    @BindView(R.id.bt_findpassword_back)
    TextView btFindpasswordBack;
    @BindView(R.id.bt_findpassword_countrycode)
    Button btFindpasswordCountrycode;
    @BindView(R.id.et_findpassword_phonenumber)
    EditTextWithDelete etFindpasswordPhonenumber;
    @BindView(R.id.et_findpassword_Verification_Code)
    EditTextWithDelete etFindpasswordVerificationCode;
    @BindView(R.id.bt_findpassword_get_Verification_Code)
    Button btFindpasswordGetVerificationCode;
    @BindView(R.id.et_findpassword_password)
    EditTextWithDelete etFindpasswordPassword;

    @BindView(R.id.bt_findpassword_findpassword)
    Button btFindpasswordFindpassword;

    @BindView(R.id.RadioButton_sign_phone)
    RadioButton RadioButtonSignPhone;
    @BindView(R.id.RadioButton_sign_email)
    RadioButton RadioButtonSignEmail;
    @BindView(R.id.rg_account)
    RadioGroup rgAccount;

    private Disposable subscription;
    Observer<NetResultData> observer = new Observer<NetResultData>() {

        @Override
        public void onError(Throwable e) {
            disMissProgressDialog();
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(NetResultData netResultData) {
            disMissProgressDialog();
            int msgCode = netResultData.getMsgCode();
            String msg = NetWorkConast.getResult(msgCode, FindPasswordActivity.this);
            if (msgCode == NetResultData.Success_Code) {
                msg = getString(R.string.find_pwd_successful);
                //finishSignIn();
            } else if (msgCode == NetResultData.Failed_Code) {
                msg = getString(R.string.find_pwd_failed);
            }
            showToast(msg);
        }
    };
    private String countryCode = "0086-";
    private String language;//中文手机号码，英文邮箱

    private boolean isPhoneAccount = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_password);
        ButterKnife.bind(this);
        showStatusBar();
        Locale locale = getResources().getConfiguration().locale;
        language = locale.getLanguage();
        isPhoneAccount = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_account_type,  "zh".equals(language));
        if(isPhoneAccount){
            RadioButtonSignPhone.setChecked(true);
        }else{
            RadioButtonSignEmail.setChecked(true);
        }

        rgAccount.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.RadioButton_sign_phone:
                        isPhoneAccount=true;
                        break;
                    case R.id.RadioButton_sign_email:
                        isPhoneAccount=false;
                        break;
                }
                changeUserAccount();
            }
        });
        //showOtherLoginWay();
        changeUserAccount();
        btFindpasswordBack.setText(Html.fromHtml(getString(R.string.findpsd_link)));

    }

    private void changeUserAccount() {

        etFindpasswordPassword.setText("");
        etFindpasswordPhonenumber.setText("");
        etFindpasswordPhonenumber.setHint(isPhoneAccount ? R.string.login_input_phone : R.string.login_input_email);
        btFindpasswordCountrycode.setVisibility(isPhoneAccount ? View.VISIBLE : View.GONE);
    }


    @OnClick({R.id.iv_switch_login, R.id.bt_findpassword_back, R.id.bt_findpassword_findpassword, R.id.bt_findpassword_countrycode, R.id.bt_findpassword_get_Verification_Code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_switch_login:
                isPhoneAccount = !isPhoneAccount;
                changeUserAccount();
                break;
            case R.id.bt_findpassword_back:
                finish();
                break;
            case R.id.bt_findpassword_countrycode:
                getCountryCode();
                break;
            case R.id.bt_findpassword_get_Verification_Code:
                getVerificationCode();
                break;
            case R.id.bt_findpassword_findpassword:
                findPassword();
                break;
        }
    }

    private void findPassword() {
        if (!NetWorkUtil.isNetworkConnected(this)) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etFindpasswordPhonenumber.getText().toString();
        String password = etFindpasswordPassword.getText().toString();

        String verCode = etFindpasswordVerificationCode.getText().toString();
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(account) || TextUtils.isEmpty(verCode)) {
            showToast(getString(R.string.fill_all_info));
            return;
        }
        if (password.length() < 6) {
            showToast(getString(R.string.psd_too_short));
            return;
        }

        Map<String, Object> map = new HashMap<>();
        if (isPhoneAccount) {
            map.put(NetWorkConast.KEY_PHONE, countryCode + account);
        } else {
            map.put(NetWorkConast.KEY_userEmail, account);
        }
        //map.put(NetWorkConast.KEY_reqType, language.equals("zh") ? NetWorkConast.ZH_CN : NetWorkConast.ZH_EN);

        map.put(NetWorkConast.KEY_userpwd, SHA1.md5Encoder(password));
        map.put(NetWorkConast.KEY_smsCode, verCode);
        NetWorkUtil.addSHA1(map);
        NetWorkUtil.getInstance().getJstyleApi().findPassword(map).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showProgressDialog(getString(R.string.Find_Passwording));
            }

        }).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
    }

    protected void finishSignIn() {
        String account = etFindpasswordPhonenumber.getText().toString();
        String password = etFindpasswordPassword.getText().toString();
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, account);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, password);
        RxBus rxBus = RxBus.getInstance();
        ActionData actionData = new ActionData();
        actionData.setAction(ActionData.FinishSignIn);
        rxBus.post(actionData);
        finish();
    }

    private void getVerificationCode() {
        if (!NetWorkUtil.isNetworkConnected(this)) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etFindpasswordPhonenumber.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast(getString(R.string.login_input_phone));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        JstyleApi jstyleApi = NetWorkUtil.getInstance().getJstyleApi();
        Observable<NetResultData> observable;
        if (isPhoneAccount) {
            observable = jstyleApi.getSmsCode(map);
            map.put(NetWorkConast.KEY_PHONE, countryCode + account);
        } else {
            observable = jstyleApi.getEmailCode(map);
            map.put(NetWorkConast.KEY_userEmail, account);
        }
        map.put(NetWorkConast.KEY_reqType, language.equals("zh") ? NetWorkConast.ZH_CN : NetWorkConast.ZH_EN);

        NetWorkUtil.addSHA1(map);

        observable.subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showProgressDialog(getString(R.string.Get_verification_codeing));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<NetResultData>() {

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData netResultData) {
                disMissProgressDialog();
                int msgCode = netResultData.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode, FindPasswordActivity.this);
                Log.i(TAG, "onNext: " + netResultData.toString());
                if (msgCode == NetResultData.Success_Code) {
                    startTimer();
                    msg = getString(R.string.Get_verification_code_sucessfule);
                }
                showToast(msg);

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
    }

//    private void showOtherLoginWay() {
//        boolean isShow = BuildConfig.APPLICATION_ID.equals("com.jstyle.jclife");
//        llLogin1.setVisibility(isShow ? View.VISIBLE : View.GONE);
//        ivSwitchLogin.setVisibility(isShow ? View.VISIBLE : View.GONE);
//
//    }

    private void getCountryCode() {
        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        phone.showForResult(this, (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                String currentId = (String) data.get("id");
                int result= (int) data.get("result");
                if(result==CountryPage.Result_OK){
                    String[] res = SMSSDK.getCountry(currentId);
                    btFindpasswordCountrycode.setText("+" + res[1]);
                    countryCode = "00" + res[1] + "-";
                }
            }
        });
    }

    private void startTimer() {
        btFindpasswordGetVerificationCode.setEnabled(false);
        Observable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Long aLong) {

                btFindpasswordGetVerificationCode.setText(String.format(getResources().getString(R.string.formatsecond), 60 - aLong));
                if (aLong == 59) {
                    btFindpasswordGetVerificationCode.setEnabled(true);
                    btFindpasswordGetVerificationCode.setText(getString(R.string.sign_get_vcode));
                    unsubscribe();
                }

            }
        });
    }

    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }
}
